#include "Game.h"
#include <string>
#include <sstream>
#include <iostream>



Game::Game(void)
{
	init();
}
Game::~Game(void)
{
	unload();
}


bool Game::init()
{
	SDL_WM_SetCaption("A BasEngine Game", NULL);
	if (TTF_Init() == -1)
	{
		printf("ERROR while loading font: %s\n", TTF_GetError());
		return false;
	}
	defaultFont = NULL;
    
    gfxEngine = new GfxEngine();
    
    keyboardState = new KeyboardState();

    player = new Player(gfxEngine);

	//write initialisationlogic here

	return true;
}
bool Game::load()
{
	defaultFont = TTF_OpenFont("../Fonts/cour.ttf", 16);
	if (defaultFont == NULL)
	{
		std::string error = TTF_GetError();
		printf("ERROR while loading font: %s\n", TTF_GetError());
		return false;
	}
	

	//write load code here

    gfxEngine->load();

	return true;
}
bool Game::unload()
{
	TTF_CloseFont(defaultFont);
	TTF_Quit();

    delete this->gfxEngine;
    delete this->player;
	//write everything to unload here


	return true;
}
bool Game::update(SDL_Event events, short fps)
{
	/*--+Event Handle+--*/
    keyboardState->preUpdate();
	while (SDL_PollEvent(&events))
    {
		switch (events.type)
		{
            case SDL_QUIT: return false; break;
            case SDL_KEYDOWN: keyboardState->update(events, true); break;
            case SDL_KEYUP: keyboardState->update(events, false); break;
		}
    }
    if (keyboardState->K_Escape.state == KeyPressed)
        return false;

    player->update(keyboardState);
    
	//TODO: write gamelogic here


	return true;
}
bool Game::draw(SDL_Surface* screen, short fps)
{
	//Clear the screen
	SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 220, 255, 160));

	//Draw Fps
	SDL_Color color = {0, 0, 0};
	std::stringstream stream;
	stream << "Fps: " << fps;
	SDL_Surface* fps_image = TTF_RenderText_Solid(defaultFont, stream.str().c_str(), color);
	SDL_Rect fps_pos;
	fps_pos.x = 12;
	fps_pos.y = 12;
	SDL_BlitSurface(fps_image, NULL, screen, &fps_pos);


	//TODO: write draw code here
    gfxEngine->draw(screen);

	if (SDL_Flip(screen) == -1)
		return false;
	return true;
}
